package cn.net.xyan.blossom.security.service

import cn.net.xyan.blossom.security.dao.SecurityPermissionDao
import cn.net.xyan.blossom.security.dao.SecurityRoleDao
import cn.net.xyan.blossom.security.dao.SecurityUserInfoDao
import cn.net.xyan.blossom.security.entity.SecurityUserInfo
import org.apache.shiro.authc.AuthenticationInfo
import org.apache.shiro.authc.AuthenticationToken
import org.apache.shiro.authz.AuthorizationInfo
import org.apache.shiro.realm.AuthorizingRealm
import org.apache.shiro.subject.PrincipalCollection
import org.springframework.beans.factory.annotation.Autowired
import org.apache.shiro.util.ByteSource
import org.apache.shiro.authc.SimpleAuthenticationInfo
import org.apache.shiro.authz.SimpleAuthorizationInfo

class BlossomAuthorizingRealm: AuthorizingRealm() {

    @Autowired
    lateinit var userDao:SecurityUserInfoDao

    @Autowired
    lateinit var roleDao:SecurityRoleDao

    @Autowired
    lateinit var permissionDao:SecurityPermissionDao

    override fun doGetAuthenticationInfo(token: AuthenticationToken?): AuthenticationInfo? {
        val username = token?.principal as String?

        val userInfo = userDao.findByUsername(username)

        return if (userInfo == null) null
        else {

            SimpleAuthenticationInfo(
                    userInfo, //用户名
                    userInfo.password, //密码
                    ByteSource.Util.bytes(userInfo.salt), //salt=username+salt
                    name  //realm name
            )
        }
    }

    override fun doGetAuthorizationInfo(principals: PrincipalCollection?): AuthorizationInfo {
        val authorizationInfo = SimpleAuthorizationInfo()
        val userInfo = principals?.primaryPrincipal as SecurityUserInfo?

        userInfo?.roles?.forEach {
            role ->
            authorizationInfo.addRole(role.role)

            role.permissions.forEach {
                permission ->
                authorizationInfo.addStringPermission(permission.permission)
            }
        }

        return authorizationInfo
    }

}